I need context many times in my fragment:
...
account.restore(getContext());
...
dbHelper = new DBHelper(getContext());
...
DiskLruBasedCache.ImageCacheParams cacheParams = new DiskLruBasedCache.ImageCacheParams(getContext(), "CacheDirectory");
...
mImageLoader = new SimpleImageLoader(getContext(), cacheParams);
...
Toast.makeText(getContext(), "err: " + error, Toast.LENGTH_LONG).show();
...
RecyclerView.LayoutManager layoutManager = new CustomLayoutManager(getContext());
...
Or should I initialize it once and then use it.
What is best way ?
Petter Hesselberg :
This is mostly a matter of preference. You can call getContext() wherever you need one -- no cause to be worried about perf overhead. Or you can assign a private Context context field in your onCreate method. Or, if a particular method has multiple uses, create a local variable.\n\nIf getContext was potentially slow, then you should definitely have stashed it, but it's really just a simple accessor (almost -- it does one bit of indirection internally).\n\nGo with whatever you find most readable.",
2017-10-10T17:23:25